package com.plantpoint.controller;

import com.plantpoint.dao.UserDao;
import com.plantpoint.entity.dto.UserInfo;
import com.plantpoint.entity.pojo.User;
import com.plantpoint.service.impl.PlantEntryServiceImpl;
import com.plantpoint.entity.bean.CommonResult;
import com.plantpoint.entity.bean.PageResult;
import com.plantpoint.entity.dto.PlantAddDTO;
import com.plantpoint.entity.dto.PlantUpdateDTO;
import com.plantpoint.entity.pojo.PlantEntry;
import com.plantpoint.entity.vo.PlantVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;



/***
 * @date   2021/4/20 0020 19:44
 * @author JackeyTower
 */
@RestController
@RequestMapping("/api/v1/plant")
public class PlantEntryController {

    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.appsecret}")
    private String appsecret;
    private PlantEntryServiceImpl plantEntryService;
    private UserDao userDao;

    public PlantEntryController(PlantEntryServiceImpl plantEntryService, UserDao userDao) {
        this.plantEntryService = plantEntryService;
        this.userDao = userDao;
    }


    @GetMapping("/plant-list/{cp}/{ps}")
    public CommonResult<PageResult<PlantEntry>> getPlantList( @PathVariable Integer cp, @PathVariable Integer ps){
        PageResult<PlantEntry> allPlant = plantEntryService.findAllPlant(cp, ps);
        return new CommonResult<>(20000,"OK",allPlant);
    }

    @PostMapping("/plant-info")
    public CommonResult<String> addPlantEntry(HttpServletRequest request,@RequestBody PlantAddDTO plantAddDTO){
        System.out.println(plantAddDTO);
        String openid = request.getAttribute("openid") + "";
        System.out.println("openid:"+openid);
        if (openid.equals("null")){
            return new CommonResult<>(40013,"OK","请先登录");
        }
        Boolean isOK = plantEntryService.save(openid, plantAddDTO);
        if (isOK==false){
            return new CommonResult<>(20004,"OK","植物名重复");
        }
        return new CommonResult<>(20000,"OK","添加成功");
    }

    @PutMapping("/plant-info")
    public CommonResult<String> updatePlantEntry(@RequestBody PlantUpdateDTO plantUpdateDTO){
        Boolean isOK = plantEntryService.updateById(plantUpdateDTO);
        if (isOK==false){
            return new CommonResult<>(50001,"ERROR","更新失败");
        }
        return new CommonResult<>(20000,"OK","更新成功");
    }

    @GetMapping("/plant-info/{id}")
    public CommonResult<PlantVO> getPlantInfo(@PathVariable String id){
        //根据id查找植物
        PlantEntry plantEntry = plantEntryService.getById(id);
        PlantVO plantVO = new PlantVO();
        //将植物封装到VO对象
        BeanUtils.copyProperties(plantEntry,plantVO);
        return new CommonResult<>(20000,"OK",plantVO);
    }

}
